package post_type

import (
	"fmt"
	"github.com/gin-gonic/gin"
	. "myplatform/handler"
	"myplatform/libs/errcode"
	"myplatform/model"
	"strconv"
)

// 根据类型找post
func GetPostBytype(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		SendRsp(c, errcode.ParamTypeError, nil)
		return
	}
	var t model.PostType
	t.Ip = uint64(id)
	if err := t.GetPostByType(); err != nil {
		SendRsp(c, errcode.SearchError, err)
		return
	}
	SendRsp(c, errcode.OK, t.Posts)
}

func GetPostBytypeHTML(c *gin.Context) {
	c.HTML(200, "type_post.html", gin.H{})
}

// 添加post和post-tupe的关联记录
func Addpostandtype(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		SendRsp(c, errcode.ParamTypeError, nil)
		return
	}
	fmt.Println("绑定参数前，pid is", id)
	// 绑定请求参数
	var req model.PostTypeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println("绑定失败", c.Request.Body)
		SendRsp(c, errcode.InvalidParams, nil)
		return
	}
	fmt.Println("ip的id为", req.IP)

	// 批量创建关联
	for _, typeID := range req.IP {
		ptm := model.PostTypeMap{
			Pid: uint64(id),
			Ip:  typeID,
		}
		if err := ptm.Create(); err != nil {
			// 处理重复创建等错误
			fmt.Printf("创建关联失败 pid:%d type:%d error:%v\n", uint64(id), typeID, err)
		}
	}
	SendRsp(c, errcode.OK, nil)
}
